package com.zd.lib.http.okhttp;


import android.os.Build;
import android.text.TextUtils;


import com.zd.lib.BuildConfig;
import com.zd.lib.config.Key;
import com.zd.lib.utils.ApiKeyUtils;
import com.zd.lib.utils.ApkUtils;
import com.zd.lib.utils.SPUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 适用于一些请求共同属性值
 * @author zoudong
 */
public class CommonRequestInterceptor implements Interceptor {
    public static final String USER_AGENT_HEADER_NAME = "User-Agent";
    private String appVersionName = BuildConfig.VERSION_NAME;
    @Override
    public Response intercept(Chain chain) throws IOException {
        return chain.proceed(transformer(chain.request()));
    }
    private  Request transformer(Request original) {
        HttpUrl.Builder builder = original.url().newBuilder();
        HttpUrl httpUrl = null;
        if (original.method().equalsIgnoreCase("GET")) {
            HttpUrl  originalurl = builder.addQueryParameter(Key.ShareKey.APPVER, appVersionName) //版本号
                    .addQueryParameter(Key.ShareKey.OS, Key.ShareKey.ANDROID).build();
            Map<String, String> map = new HashMap<>();
            //获取 GET 参数
            for (String str : originalurl.queryParameterNames()) {
                map.put(str, originalurl.queryParameter(str));
            }
            Request.Builder requestBuilder = original.newBuilder()
                    .url(originalurl);
            return requestBuilder.build();
        } else if (original.method().equalsIgnoreCase("POST")) {
            Map<String, String> map = new HashMap<>();
            //获取 POST 参数
            if (original.body() instanceof FormBody) {
                FormBody body = (FormBody) original.body();
                int size = body.size();
                for (int i = 0; i < size; i++) {
                    map.put(body.name(i), body.value(i));
                }
            }
            FormBody.Builder build = new FormBody.Builder();
            for (String key : map.keySet()) {
                    String value = map.get(key);
                if (!TextUtils.isEmpty(value)) {
                    build.add(key, value);
                }
            }
            Request.Builder  requestbuild = original.newBuilder().post(build.build());
            return requestbuild.build();
        }
        return original;
    }


}
